package service

import (
	"MxShopApi/global"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
)

// 初始化
func NewPayClient() *alipay.Client {
	var err error
	if global.AliPayClient, err = alipay.New(global.ServerConfig.AliPay.KAppId, global.ServerConfig.AliPay.KPrivateKey, false); err != nil {
		zap.S().Info("警告::: ", "你已经报错了还写个屁！！！")
	}
	//加载公钥
	global.AliPayClient.LoadAliPayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjIyIMwE9Qo3pYZA/pMzqBYnupfiIRo3ssFKzk4V6jW4qUFMfROZHCA/EM480G1VStkNEyKOku+yv/e94xmgimRzd4Ql8IsgIUTrWguryeUQdU+WgOUNgpM+l/u9SmB236wk2N2BITCM5wa2oD3RJnmvN+2iAJi3SZfZeccAuvIami3+YlEdP7+2ZUx7iNXwXSxB9O7llWo8rD6WhPyxidbFfAyGOo9frm4Xu89ZFbDx7HCI5Cm+wpm6hWARdyzDS7XB4u2avYr53M5wG0z4xUZAMB0ua8QqhThW/hDHEvtrUcyYxbWwqI7waXW5inBY16pPXXvZopp94i9iCVrAf0wIDAQAB")
	return global.AliPayClient
}

// 订单支付
func Pay(orderSnc string, price string) string {
	NewPayClient()
	var p = alipay.TradePagePay{}
	p.NotifyURL = global.ServerConfig.AliPay.KServerDomain + "/v1/ali/notify"
	p.ReturnURL = "http://www.baidu.com"
	p.Subject = "支付测试:" + orderSnc
	p.OutTradeNo = orderSnc
	p.TotalAmount = price
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"
	url, _ := global.AliPayClient.TradePagePay(p)
	return url.String()
}

// 退款
func Refund(tradeNo string, refundAmount string) *alipay.TradeRefundRsp {
	NewPayClient()
	var p = alipay.TradeRefund{}
	p.RefundAmount = refundAmount
	p.TradeNo = tradeNo
	result, err := global.AliPayClient.TradeRefund(p)
	if err != nil {
		zap.S().Info("退款失败", err)
	}
	return result
}
